using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using Repository.Abstract;
using DomainModel.Entities;
using Repository.Concrete;
using Service.Abstract;
using System.Web.Mvc;

namespace Service.Concrete
{
    public class TaskService : BaseService<Task>, ITaskService
    {
        private readonly ITaskRepository _taskRepository;

        public TaskService(ITaskRepository taskRepository) : base(taskRepository)
        {
            _taskRepository = taskRepository;
        }

        public IQueryable<Task> GetTasksByProject(User user, int projectId)
        {
            var task = _taskRepository.GetAll.Where(t => t.UserId == user.UserId && t.ProjectId == projectId);
            return task;
        }

        public IEnumerable<Task> GetTasksByDate(User user, int dateSpan1, int dateSpan2)
        {
            var tasks = _taskRepository.GetAll.Where(p => p.UserId == user.UserId);
            var result = new List<Task>();
            var date = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);

            foreach (var task in tasks)
            {
                if(task.DateDue != null)
                {
                    if (task.DateDue < date.AddDays(dateSpan2)) 
                    {
                        if (task.DateDue.Value > date.AddDays(dateSpan1))
                        {
                            result.Add(task);
                        }
                    }
                }
            }

            return (IEnumerable<Task>) result;
        }

        public Task GetTaskById(int taskId)
        {
            var projectService = new ProjectService();
            var task = _taskRepository.GetAll.Where(p => p.Id == taskId).SingleOrDefault();
            if (task.ProjectId != null)
            {
                task.Project = projectService.GetProjectById((int)task.ProjectId);
            }
            return task;
        }

        public override void Add(Task entity, Guid userId)
        {
            entity.Flagged = false;
            base.Add(entity, userId);
        }
    }
}